/* 测试MySQL C语言开发库接口 */

#include <unistd.h>
#include <mysql/mysql.h>
#include <iostream>
using namespace std;

int main()
{
    // 1.初始化mysql操作句柄
    MYSQL* _mysql = mysql_init(NULL);
    if(_mysql == NULL)
    {
        cout << "mysql_init failed" << endl;
        return 0;
    }

    // 2.连接mysql服务端
    /* 
     * 函数原型：
     * mysql_real_connect(MYSQL *mysql, //mysql操作句柄
     *      const char *host,  //服务端IP地址
     *      const char *user,  //用户名
     *      const char *passwd, //密码
     *      const char *db,     //数据库
     *      unsigned int port,  //端口
     *      const char *unix_socket,  //是否使用本地域套接字
     *      unsigned long client_flag  //数据库标志位， 通常为0， 采用默认属性
     * )
     * 连接成功，返回连接的操作句柄，否则返回NULL
    */
    MYSQL* ret = mysql_real_connect(_mysql, "101.43.7.28", "root", "19683250", "chat_system", 3306, NULL, 0);
    if(ret == NULL)
    {
        cout << "mysql_real_connect failed" << endl;
        
        // 需释放操作句柄
        mysql_close(_mysql);
        return 0;
    }
    
    // 3.设置连接对应的数据库字符集
    mysql_set_character_set(_mysql, "utf8");
    
    cout << "mysql_real_connect successful" << endl;
    
    // 4.执行sql语句
    //char buf[1024] = "insert into user(userid, nickname, sex, school, telnum, passwd)values(1, 'dyh', 'm', 'xgc', 111, 111)";
    
    char buf[1024] = "select * from user";
    int fun_ret = mysql_query(_mysql, buf); 
    if(fun_ret != 0)
    {
        cout << "mysql_query failed" << endl;
        mysql_close(_mysql);
        return 0;
    }
    cout << "mysql_query success" << endl; 

    // 5.获取结果集
    MYSQL_RES* m_res = mysql_store_result(_mysql);
    if(m_res == NULL)
    {
        cout << "mysql_store_result failed" << endl;
        mysql_close(_mysql);
        return 0;
    }

    // 6.获取结果集行数
    int rows = mysql_num_rows(m_res);
    for(int i = 0; i < rows; ++i)
    {
        // 7.获取结果集的一行数据
        MYSQL_ROW row = mysql_fetch_row(m_res);
        cout << row[0] << ":" << row[1] << ":" << row[2] << ":" << row[3] << ":" << row[4] << ":" << row[5] << ":" << row[6] << endl;
    }

    // 释放结果集、关闭MySQL句柄
    mysql_free_result(m_res);
    mysql_close(_mysql);

    return 0;
}
